package com.bdzl.pub.util.param;

import lombok.Data;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 查询参数
 */
@Data
public class Query extends LinkedHashMap<String, Object> {
	private static final long serialVersionUID = 1L;
	// 游标
	private int offset;
	// 每页条数
	private int limit;
	//页码，可为空,优先offset再用page，两者传一个就可以了
	private int page;

	public Query(Map<String, Object> params) {
		if(params == null) {
			this.putAll(new HashMap<>());
		} else {
			this.putAll(params);
		}
		
		if(params == null || !params.containsKey("limit")) {
			this.limit = 10;
		} else {
			this.limit = Integer.parseInt(params.get("limit").toString());
		}
		// 分页参数
		if(params == null || !params.containsKey("offset")) {
			if(!params.containsKey("page")) {
				this.offset = 0;
			}else {
				this.page = Integer.parseInt(params.get("page").toString());
				if(page <= 0)  page = 1;
				this.offset = (page - 1) * limit;
			}
		} else {
			this.offset = Integer.parseInt(params.get("offset").toString());
		}		
		
		this.put("offset", offset);
		this.put("page", offset / limit + 1);
		this.put("limit", limit);
	}
	public void setOffset(int offset) {
		this.put("offset", offset);
	}
}
